package com.example.jspwork.Servlet;


import com.example.jspwork.Dao.AddressQuery;
import com.example.jspwork.pojo.nowBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import com.example.jspwork.utils.MyUtil;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@WebServlet("/api/manage")
public class ManageServlet extends HttpServlet {

    private List<nowBean> nowinfo_list = initInfoList();

    /**
     * 初始化info_list成员
     */
    private List<nowBean> initInfoList() {
        List<nowBean> tmp_list = new ArrayList<>();
        tmp_list.add(new nowBean(1,"北京","多云",36,24,2,"南风","<3级",MyUtil.DTStr(LocalDateTime.now())));
        tmp_list.add(new nowBean(1,"天津","晴",36,24,2,"南风","<3级",MyUtil.DTStr(LocalDateTime.now())));
        tmp_list.add(new nowBean(1,"成都","阴",36,24,2,"南风","<3级",MyUtil.DTStr(LocalDateTime.now())));

        return tmp_list;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        nowinfo_list = queryManage();
        String jsonData=getJsonData();
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(jsonData);


    }

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        /**
//         * 用MVC方式，转发带数据的request到目标JSP页面
//         */
//        nowinfo_list = queryManage();
//        String jsonData=getJsonData();
//        resp.setContentType("application/json");
//        resp.setCharacterEncoding("UTF-8");
//        resp.getWriter().write(jsonData);
//
//
//
////        req.setAttribute("list", info_list);
////        //转发
////        req.getRequestDispatcher("/manage.jsp").forward(req,resp);
//    }

    private List<nowBean> queryManage() {

        List<nowBean> list;
        list = AddressQuery.queryManage();

        return list;
    }
    public String getJsonData() {
//        List<nowBean> infoList = nowinfo_list();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonData = mapper.writeValueAsString(nowinfo_list);
            return jsonData;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
